package org.jeecg.modules.data.controller;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.data.entity.District;
import org.jeecg.modules.data.entity.DistrictTree;
import org.jeecg.modules.data.service.IDistrictService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: district
 * @Author: jeecg-boot
 * @Date:   2025-02-12
 * @Version: V1.0
 */
@Api(tags="district")
@RestController
@RequestMapping("/verifi/district")
@Slf4j
public class DistrictController extends JeecgController<District, IDistrictService> {
	@Autowired
	private IDistrictService districtService;
/**
	 * 分页列表查询
	 *
	 * @param district
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "district-分页列表查询")
	@ApiOperation(value="district-分页列表查询", notes="district-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<District>> queryPageList1(District district,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<District> queryWrapper = QueryGenerator.initQueryWrapper(district, req.getParameterMap());
		Page<District> page = new Page<District>(pageNo, pageSize);
		IPage<District> pageList = districtService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param district
	 * @return
	 */
	@AutoLog(value = "district-添加")
	@ApiOperation(value="district-添加", notes="district-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody District district) {
		districtService.save(district);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param district
	 * @return
	 */
	@AutoLog(value = "district-编辑")
	@ApiOperation(value="district-编辑", notes="district-编辑")
	@PostMapping(value = "/edit")
	public Result<String> edit(@RequestBody District district) {
		UpdateWrapper<District> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("cant_code", district.getCantCode());
		districtService.update(district,updateWrapper);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "district-通过id删除")
	@ApiOperation(value="district-通过id删除", notes="district-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		districtService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "district-批量删除")
	@ApiOperation(value="district-批量删除", notes="district-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.districtService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "district-通过id查询")
	@ApiOperation(value="district-通过id查询", notes="district-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<District> queryById(@RequestParam(name="id",required=true) String id) {
		District district = districtService.getById(id);
		if(district==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(district);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param district
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, District district) {
        return super.exportXls(request, district, District.class, "district");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, District.class);
    }

	 /**
	  * 查询数据 查出所有区域,并以树结构数据格式响应给前端
	  *
	  * @return
	  */
	 @ApiOperation(value="district-查树", notes="district-查树")
	 @RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
	 public Result<List<DistrictTree>> queryTreeList(@RequestParam(name = "ids", required = false) String ids) {
		 Result<List<DistrictTree>> result = new Result<>();
		 try {
			 if(oConvertUtils.isNotEmpty(ids)){
				 List<DistrictTree> departList = districtService.queryTreeList(ids);
				 result.setResult(departList);
			 }else{
				 List<DistrictTree> list = districtService.queryTreeList();
				 result.setResult(list);
			 }
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }

	 /**
	  * 分页列表查询
	  *
	  * @param district
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "district-分页列表查询")
	 @ApiOperation(value="district-分页列表查询", notes="district-分页列表查询")
	 @GetMapping(value = "/rootList")
	 public Result<IPage<District>> queryPageList(District district,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  HttpServletRequest req) {
		 String hasQuery = req.getParameter("hasQuery");
		 if(hasQuery != null && "true".equals(hasQuery)){
			 QueryWrapper<District> queryWrapper =  QueryGenerator.initQueryWrapper(district, req.getParameterMap());
			 List<District> list = districtService.queryTreeListNoPage(queryWrapper);
			 IPage<District> pageList = new Page<>(1, 10, list.size());
			 pageList.setRecords(list);
			 return Result.OK(pageList);
		 }else{
			 String parentId = district.getPid();
			 if (oConvertUtils.isEmpty(parentId)) {
				 parentId = "CN";
			 }
			 district.setPid(null);
			 QueryWrapper<District> queryWrapper = QueryGenerator.initQueryWrapper(district, req.getParameterMap());
			 // 使用 eq 防止模糊查询
			 queryWrapper.eq("pid", parentId);
			 Page<District> page = new Page<District>(pageNo, pageSize);
			 IPage<District> pageList = districtService.page(page, queryWrapper);
			 return Result.OK(pageList);
		 }
	 }

	 /**
      * 获取子数据
      * @param district
      * @param req
      * @return
      */
	//@AutoLog(value = "district-获取子数据")
	@ApiOperation(value="district-获取子数据", notes="district-获取子数据")
	@GetMapping(value = "/childList")
	public Result<IPage<District>> queryPageList(District district,HttpServletRequest req) {
		QueryWrapper<District> queryWrapper = QueryGenerator.initQueryWrapper(district, req.getParameterMap());
		List<District> list = districtService.list(queryWrapper);
		IPage<District> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
		return Result.OK(pageList);
	}

	 /**
	  * 批量查询子节点
	  * @param parentIds 父ID（多个采用半角逗号分割）
	  * @return 返回 IPage
	  * @param parentIds
	  * @return
	  */
	 //@AutoLog(value = "district-批量获取子数据")
	 @ApiOperation(value="district-批量获取子数据", notes="district-批量获取子数据")
	 @GetMapping("/getChildListBatch")
	 public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
		 try {
			 QueryWrapper<District> queryWrapper = new QueryWrapper<>();
			 List<String> parentIdList = Arrays.asList(parentIds.split(","));
			 queryWrapper.in("pid", parentIdList);
			 List<District> list = districtService.list(queryWrapper);
			 IPage<District> pageList = new Page<>(1, 10, list.size());
			 pageList.setRecords(list);
			 return Result.OK(pageList);
		 } catch (Exception e) {
			 log.error(e.getMessage(), e);
			 return Result.error("批量查询子节点失败：" + e.getMessage());
		 }
	 }

}
